// pages/my/my.js
Page({
  data: {
    userInfo: {}, // 用户信息
    publishedList: [], // 已发布的信息列表
    publishedCount: 0 // 发布数量
  },

  onLoad: function (options) {
    this.checkLoginStatus();
  },

  onShow: function () {
    // 每次显示页面时刷新数据
    if (this.data.userInfo.nickName) {
      this.loadPublishedList();
    }
  },

  // 检查登录状态
  checkLoginStatus: function () {
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({
        userInfo: userInfo
      });
      this.loadPublishedList();
    }
  },

  // 用户登录
  login: function () {
    wx.login({
      success: (res) => {
        if (res.code) {
          // 确保openid已获取
          this.ensureOpenid(() => {
            // 这里可以调用后端接口获取用户信息
            // 暂时使用简化的用户信息存储
            const mockUserInfo = {
              nickName: '微信用户',
              avatarUrl: '' // 可以设置默认头像
            };

            wx.setStorageSync('userInfo', mockUserInfo);
            this.setData({
              userInfo: mockUserInfo
            });
            this.loadPublishedList();
            wx.showToast({
              title: '登录成功',
              icon: 'success'
            });
          });
        }
      },
      fail: (err) => {
        console.log('登录失败', err);
        wx.showToast({
          title: '登录失败',
          icon: 'error'
        });
      }
    });
  },

  // 确保openid已获取
  ensureOpenid: function (callback) {
    const openid = wx.getStorageSync('openid');
    if (openid) {
      // openid 已存在，直接执行回调
      callback && callback();
    } else {
      // openid 不存在，调用云函数获取
      wx.cloud.callFunction({
        name: 'init',
        success: res => {
          wx.setStorageSync('openid', res.result.openid);
          callback && callback();
        },
        fail: err => {
          console.error('获取openid失败', err);
          wx.showToast({
            title: '获取用户信息失败，请重试',
            icon: 'error'
          });
        }
      });
    }
  },

  // 加载已发布的信息列表
  loadPublishedList: function () {
    wx.showLoading({
      title: '加载中...'
    });

    const db = wx.cloud.database();
    const openid = wx.getStorageSync('openid');

    if (!openid) {
      wx.hideLoading();
      return;
    }

    db.collection('carpool')
      .where({
        _openid: openid
      })
      .orderBy('createTime', 'desc')
      .get()
      .then(res => {
        wx.hideLoading();
        const list = res.data.map(item => ({
          ...item,
          createTime: this.formatTime(new Date(item.createTime)),
          date: item.date,
          time: item.time
        }));

        this.setData({
          publishedList: list,
          publishedCount: list.length
        });
      })
      .catch(err => {
        console.error('加载发布列表失败', err);
        wx.hideLoading();
        wx.showToast({
          title: '加载失败',
          icon: 'error'
        });
      });
  },

  // 跳转到发布页面
  goToPublish: function (e) {
    if (!this.data.userInfo.nickName) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    const type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: `/pages/publish/publish?type=${type}`
    });
  },

  // 跳转到详情页
  goToDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`
    });
  },

  // 编辑信息
  editItem: function (e) {
    e.stopPropagation(); // 阻止事件冒泡
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/edit/edit?id=${id}`
    });
  },

  // 下架信息
  deleteItem: function (e) {
    e.stopPropagation(); // 阻止事件冒泡
    const id = e.currentTarget.dataset.id;

    wx.showModal({
      title: '确认下架',
      content: '确定要下架这条信息吗？下架后其他人将看不到这条信息。',
      success: (res) => {
        if (res.confirm) {
          this.updateItemStatus(id, 'inactive');
        }
      }
    });
  },

  // 更新信息状态
  updateItemStatus: function (id, status) {
    wx.showLoading({
      title: '处理中...'
    });

    const db = wx.cloud.database();
    db.collection('carpool').doc(id).update({
      data: {
        status: status,
        updateTime: new Date()
      }
    }).then(res => {
      wx.hideLoading();
      wx.showToast({
        title: status === 'inactive' ? '已下架' : '已重新发布',
        icon: 'success'
      });
      this.loadPublishedList(); // 重新加载列表
    }).catch(err => {
      console.error('更新状态失败', err);
      wx.hideLoading();
      wx.showToast({
        title: '操作失败',
        icon: 'error'
      });
    });
  },

  // 格式化时间
  formatTime: function (date) {
    const now = new Date();
    const diff = now - date;
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (days === 0) {
      return '今天';
    } else if (days === 1) {
      return '昨天';
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
});
